const jwt = require('jsonwebtoken');
const jsonParse = require('../lib/jsonParse')
const secret = require('../config/keys')
// token 数据库集合
// const Tokens = require('../schemas/users').Tokens;
// 接口集合
const xiecheng = require('./model/xiecheng')
const common = require('./model/common')
const wenjuan = require('./model/wenjuan')

module.exports = {
    // 携程
    ...xiecheng,
    // 公共方法
    ...common,
    // 问卷
    ...wenjuan,
    // 接口不存在
    noHandler: (request, response) => {
        jsonParse.sendResult(response, 404, '接口不存在')
    },
    // 验证Token
    verifyLogin: (request, response, handler) => {
        if (request.headers['authorization']) {
            const token = request.headers['authorization'].replace('Bearer ', '');
            // Tokens.findOne({token}).then(res => {
            //     if(res){
            jwt.verify(token, secret.secretOrKey, function (err, data) {
                if (err) {
                    if (err.name == 'TokenExpiredError') {
                        jsonParse.sendResult(response, '-101')
                    } else if (err.name == 'JsonWebTokenError') {
                        jsonParse.sendResult(response, '-102')
                    }
                } else {
                    const decodeResult = jwt.decode(token)
                    let userName = decodeResult.userName
                    handler(request, response, userName)
                }
            })
            // } else {
            //     jsonParse.sendResult(response, '-103')
            // }
            // })

        } else {
            jsonParse.sendResult(response, '-103')
        }
    }
}